/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.coupon.service.impl.Coupon3rdServiceImpl
   Module Description   :

   Date Created      : 2011/8/9
   Original Author   : jeffma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.coupon.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.dao.ObjectDao;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.ec.coupon.entity.Coupon3rd;
import com.yaodian100.ec.coupon.entity.Coupon3rdItem;
import com.yaodian100.ec.coupon.service.Coupon3rdService;
import com.yaodian100.ec.order.entity.OrderProduct;
import com.yaodian100.ec.order.entity.Orders;

/**
 * @author jeffma
 * 
 */
public class Coupon3rdServiceImpl extends DomainServiceImpl<Coupon3rd> implements Coupon3rdService {

	private String checkDate = "9999";
	private List<Coupon3rd> activeCampaigns = new ArrayList();
	private ObjectDao<Coupon3rdItem> itemDao;

	/**
	 * @param itemDao the itemDao to set
	 */
	public void setItemDao(ObjectDao<Coupon3rdItem> itemDao) {
		this.itemDao = itemDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.coupon.service.Coupon3rdService#getActive(com.yaodian100.ec.order.entity.Orders)
	 */
	@Override
	public Coupon3rd getActive(Orders order) {
		String nowString = DateUtil.convertDateToString("yyMMddHH", order.getOrderDt());
		if (!nowString.equals(checkDate)) {
			CommonCriteria cri = new CommonCriteria();
			cri.addGe("endDate", order.getOrderDt());
			cri.addLe("startDate", order.getOrderDt());
			activeCampaigns = getList(0, -1, cri, null);
			logger.info("renew activeCampaigns:{}", activeCampaigns);
			// 每 1hr 更新一次
			checkDate = DateUtil.convertDateToString("yyMMddHH", order.getOrderDt());
		}
		return getValidCampaignByObj(activeCampaigns, order);
	}

	private Coupon3rd getValidCampaignByObj(List<Coupon3rd> coupons, Orders order) {
		Coupon3rd result = null;
		for (Coupon3rd c : coupons) {
			if (!c.getPaymentTypeArray().contains(order.getPaymentTp())) {
				continue;
			}

			if (Coupon3rd.Range.Site.equals(c.getRange())) {
				result = c;
				break;
			} else if (Coupon3rd.Range.Product.equals(c.getRange())) {
				for (OrderProduct op : order.getOrderProduct()) {
					if (c.getRangeExtIds().contains(op.getProdId())) {
						result = c;
						break;
					}
				}
			} else if (Coupon3rd.Range.Category.equals(c.getRange())) {
				// 馆线适用待确认
				for (String s : c.getRangeExtList()) {
					for (OrderProduct op : order.getOrderProduct()) {
						if (op.getCategoryPath().startsWith(s + "/") || op.getCategoryPath().equals(s)) {
							result = c;
							break;
						}
					}
				}
			}
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.coupon.service.Coupon3rdService#regCoupon(com.yaodian100.ec.coupon.entity.Coupon3rd,
	 * com.yaodian100.ec.order.entity.Orders)
	 */
	@Override
	@Transactional(readOnly = false)
	public Coupon3rdItem regCoupon(Coupon3rd coupon3rd, Orders order) {
		Coupon3rdItem item = null;
		Date now = new Date(System.currentTimeMillis());

		CommonCriteria cri = new CommonCriteria();
		cri.addEq("coupon.uuid", coupon3rd.getUuid());
		cri.addEq("orderId", order.getOrderId());
		List<Coupon3rdItem> items = itemDao.getList(cri, null);
		if (items != null && items.size() > 0) {
			// 如果发过 coupon 传之前的讯息回去
			return items.get(0);
		}

		cri = new CommonCriteria();
		cri.addEq("coupon.uuid", coupon3rd.getUuid());
		cri.addEq("memberId", null);
		// 改用 list page 取得 50 個未用 couponItem, 隨機取得一個
		items = itemDao.getListPageable(cri, null, 0, 50);
		if (items.size() > 1) {
			item = items.get(RandomUtils.nextInt(items.size()));
		}
		if (item != null) {
			item.setMemberId(order.getMemberId());
			item.setOrderId(order.getOrderId());
			item.setUseDate(now);
			itemDao.saveOrUpdate(item);
		} else {
			logger.warn("memberId: {} get coupon:{} fail, size:{}", new Object[] { order.getMemberId(), coupon3rd.getUuid(),
					items.size() });
		}
		return item;
	}

}
